package xin.marcher.wind.consistency.sharding;

import org.springframework.stereotype.Component;
import xin.marcher.wind.consistency.config.TendConsistencyConfiguration;
import xin.marcher.wind.consistency.election.PeerElectionHandler;
import xin.marcher.wind.consistency.sharding.strategy.AverageAllocationConsistencyTaskShardingStrategy;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 分片处理器
 *
 * @author marcher
 **/
@Component
public class ConsistencyTaskShardingHandler {


    /**
     * 一致性任务配置
     */
    @Resource
    private TendConsistencyConfiguration tendConsistencyConfiguration;
    /**
     * 选举处理器
     */
    @Resource
    private PeerElectionHandler peerElectionHandler;

    /**
     * 对任务做分片
     *
     * @param peersConfigList 节点信息列表
     */
    public void doTaskSharding(List<String> peersConfigList) {
        // 获取配置文件中配置的任务分片数
        Long taskShardingCount = tendConsistencyConfiguration.taskShardingCount;
        // 如果用户没有自定义任务分片类，使用内部已经定义好的分片类，进行分片。
        Map<String, List<Long>> taskShardingResult = AverageAllocationConsistencyTaskShardingStrategy
                .getInstance()
                .sharding(peersConfigList, taskShardingCount);
        // 分发已完成分片的事件给选举处理器
        peerElectionHandler.eventBus.post(taskShardingResult);
    }

}
